package com.zkw.concurrent.executors

import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

/**
 * Created by Administrator on 2016/4/8.
 *
 */
class ScheduledExecutorServiceMain {
    /*
    * 延后多长时间执行线程任务 有任务返回值
    * If any execution of the given task throws an exception, the task is no longer executed.
    * */
    def scheduleTest(){
        ExecutorService executorService = Executors.newScheduledThreadPool(5);
        ScheduledFuture scheduledFuture = executorService.schedule(new Callable() {
            @Override
            Object call() throws Exception {
                println 'schedule Executed!'
                return 'return schedule'
            }
        },6,TimeUnit.SECONDS)
        println 'result= '+scheduledFuture.get()
        executorService.shutdown()
    }
    /*
    * 固定频率执行线程任务 没有任务返回值
    * 如果线程任务在下一次调度时没有执行完，下一次调度不会执行直到这次任务执行完。一次只能执行一个任务
    * a delay between the start of the previous execution, until the start of the next execution.
    * */
    def scheduleAtFixedRateTest(){
        ExecutorService executorService = Executors.newScheduledThreadPool(5)
        ScheduledFuture scheduledFuture = executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            void run() {
                println 'scheduleAtFixedRateTest execute'
                Thread.sleep(9000)
            }
        },2,5,TimeUnit.SECONDS)
        println scheduledFuture.get()
        executorService.shutdown()
    }
    /*
    * 固定频率执行线程任务 没有任务返回值
    * delay between the end of the previous execution, until the start of the next.
    * */
    def scheduleWithFixedDelayTest(){
        ExecutorService executorService = Executors.newScheduledThreadPool(5)
        ScheduledFuture scheduledFuture = executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            void run() {
                println 'scheduleWithFixedDelayTest execute'
                Thread.sleep(9000)
            }
        },2,5,TimeUnit.SECONDS)
        println scheduledFuture.get()
        executorService.shutdown()
    }


    public static void main(String[] args) {
        def main = new ScheduledExecutorServiceMain()
//        main.scheduleTest()
//        main.scheduleAtFixedRateTest()
        main.scheduleWithFixedDelayTest()
    }
}
